Functions And Software Development Workflow

Some key concepts

  • Function signature: its name, inputs, and outputs
  • Use notebooks for (a) exploratory development and (b) results presentation. Don't use notebooks to contain significant code.
  • To use a function inside a notebook, you must import its containint module.

Iterative development of a function

Construct a function that tests if a number is prime.


In [ ]:
5 / 3

In [ ]:
5 % 3

In [ ]:
import numpy as np
value = 4
is_prime = True
upper = int(np.ceil(np.sqrt(value)))
for divisor in range(2, upper+1):
    if value % divisor == 0:
        is_prime = False
        break
print(is_prime)

In [ ]:
value = 4
def isPrime(value):
    is_prime = True
    upper = int(np.ceil(np.sqrt(value)))
    if value == 2:  # THIS IS TERRIBLE
        return is_prime
    for divisor in range(2, upper+1):
        if value % divisor == 0:
            is_prime = False
            break
    return is_prime

In [ ]:
for val in range(2, 20):
    print("%d: %d" % (val, isPrime(val)))

Put the function in a python module


In [2]:
import is_prime
is_prime.isPrime(4)


Out[2]:
False

In [4]:
for val in range(2, 20):
    print("%d: %d" % (val, is_prime.isPrime(val)))


2: 1
3: 1
4: 0
5: 1
6: 0
7: 1
8: 0
9: 0
10: 0
11: 1
12: 0
13: 1
14: 0
15: 0
16: 0
17: 1
18: 0
19: 1

Use the function in a function

Write a function that lists the prime numbers less than a threshold.

Exercise: Put this new function into a different python module and call it from the notebook.